#!/bin/bash
# postinst script for _-_PACKAGENAME_-_
#
# see: dh_installdeb(1)

set -e
# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

#DEBHELPER#

. /usr/share/debconf/confmodule

TMP_M4_FILE=/usr/share/packaged-site/_-_PACKAGENAME_-_/postinst.m4.tmp

# installed by the package
DYNAMIC_CONF_TEMPLATE=/usr/share/packaged-site/_-_PACKAGENAME_-_/_-_PACKAGENAME_-_.dynamic.yml.template
# written to by m4 for our dynamic param handling
# hand then written to by dbconfigcommon
DYNAMIC_CONF_TEMPLATE2=/usr/share/packaged-site/_-_PACKAGENAME_-_/dynamic.yml.template.2
DYNAMIC_CONF_PATH=/etc/packaged-site/_-_PACKAGENAME_-_/dynamic.yml
DYNAMIC_CONF_WWWPATH=/var/www/_-_PACKAGENAME_-_/app/_-_APPNAME_-_/config/dynamic.yml

__POSTINST.CONSTANTS.WEB__
__POSTINST.CONSTANTS.DB__

FIRSTTIMEINSTALL=0

case "$1" in
    configure)
        if [ "$2" = "" ] || [ "$2" = "0" ] ; then
            FIRSTTIMEINSTALL=1
        fi

        # In the case that this file already exists, delete it first
        rm -f $TMP_M4_FILE

        # Build up the m4 templating file:
        touch $TMP_M4_FILE

        # make sure the webserver can write to the app cache and logs
        if [ -e  _-_WWWROOT_-_/app/_-_APPNAME_-_/cache ]; then
            rm -rf _-_WWWROOT_-_/app/_-_APPNAME_-_/cache/* #clear it #TODO replace this with app/APP/console
            chown -R www-data _-_WWWROOT_-_/app/_-_APPNAME_-_/cache
        fi
        if [ -e  _-_WWWROOT_-_/app/_-_APPNAME_-_/logs ]; then
            chown -R www-data _-_WWWROOT_-_/app/_-_APPNAME_-_/logs
        fi

        __POSTINST.CONFIGURE.WEB__
        __POSTINST.CONFIGURE.DB__

        __POSTINST.CONFIGURE.DYNAMIC__


        if [ -e $DYNAMIC_CONF_TEMPLATE2 ]; then
            m4 $TMP_M4_FILE  $DYNAMIC_CONF_TEMPLATE2 > $DYNAMIC_CONF_PATH;
        elif [ -e $DYNAMIC_CONF_TEMPLATE ]; then
            m4 $TMP_M4_FILE  $DYNAMIC_CONF_TEMPLATE > $DYNAMIC_CONF_PATH;
        fi


        # link it from its final path into the symfony2 app config directory
        if [[ ! -h $DYNAMIC_CONF_WWWPATH && -e $DYNAMIC_CONF_PATH ]]; then
            ln -s $DYNAMIC_CONF_PATH $DYNAMIC_CONF_WWWPATH
        fi

        __POSTINST.CONFIGURE.END.DB__
        __POSTINST.CONFIGURE.END.WEB__

        rm -rf $TMP_M4_FILE;
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

db_stop
exit 0
